package com.rice.riceapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.rice.riceapiclientsdk.entity.User;

import java.util.HashMap;
import java.util.Map;

/**
 * 客户端控制类
 * @author 米饭好好吃
 */
public class ApiClient {
    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    private String genSign(String randomStr, String timeStamp) {
        Digester digester = new Digester(DigestAlgorithm.SHA256);
        String originInfo = accessKey + randomStr + timeStamp + secretKey;
        return digester.digestHex(originInfo);
    }

    private String genBody(String name) {
        // 1. 生成随机数
        String randomStr = RandomUtil.randomInt(1000, 10000) + "";
        // 2. 生成时间戳
        String timeStamp = System.currentTimeMillis() + "";
        // 3. sign生成
        String sign = genSign(randomStr, timeStamp);
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("name", name);
        bodyMap.put("accessKey", accessKey);
        bodyMap.put("randomNum", randomStr);
        bodyMap.put("timeStamp", timeStamp);
        bodyMap.put("sign", sign);
        // 4. 序列化bodyMap
        return JSONUtil.toJsonStr(bodyMap);
    }

    public String getNameByGet(String name) {
        // 1. 通过HttpUtil发起请求
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("name", name);
        String res = HttpUtil.get("http://127.0.0.1:8123/api/name/", paramsMap);
        // 2. 返回响应类型
        return res;
    }

    public String getNameByPost(String name) {
        // 1. 通过HttpUtil发起请求
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("name", name);
        String res = HttpUtil.post("http://localhost:8123/api/name/", paramsMap);
        // 2. 返回响应类型
        return res;
    }

    public String getNameByPostUser(User user) {
        // 1. 使用HttpRequest发起请求
        String url = "http://localhost:8123/api/name/user";
        String name = user.getName();
        String body = genBody(name);
        String res = HttpRequest.post(url)
                .body(body)
                .execute()
                .body();
        // 3. 返回响应内容
        return res;
    }
}
